/*
 * Copyright 2025-2026 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package glz.hawk.app;

import glz.hawk.bookstore.mapper.BookMapper;
import glz.hawk.bookstore.model.Book;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import static glz.hawk.bookstore.mapper.BookDynamicSqlSupport.*;
import static org.mybatis.dynamic.sql.SqlBuilder.isIn;
import static org.mybatis.dynamic.sql.SqlBuilder.select;

/**
 * This class is responsible for
 *
 * @author Zhang Peng
 */
@SpringBootApplication
@MapperScan("glz.hawk.bookstore.mapper")
public class MybatisExampleApplication {

    private static final Random random = new Random();
    @Autowired
    private BookMapper bookMapper;

    public static void main(String[] args) {
        try (ConfigurableApplicationContext context = SpringApplication.run(MybatisExampleApplication.class, args)) {
            MybatisExampleApplication app = context.getBean(MybatisExampleApplication.class);
//            app.createBooks();
            app.createBook(false);
//            app.queryBook();
        }
    }

    public static String generateNumberOnlyString() {
        StringBuilder sb = new StringBuilder(10);
        for (int i = 0; i < 10; i++) {
            // 第一位避免为0（如需允许0开头可直接用random.nextInt(10)）
            if (i == 0) {
                sb.append(random.nextInt(9) + 1); // 1-9
            } else {
                sb.append(random.nextInt(10)); // 0-9
            }
        }
        return sb.toString();
    }

    public List<Book> queryBook() {
        SelectStatementProvider selectStatementProvider = select(bookId, bookName, isbn)
            .from(book)
            .where(bookId, isIn(BigDecimal.valueOf(1755585882264L)))
            .build()
            .render(RenderingStrategies.MYBATIS3);
        System.out.println(selectStatementProvider.getSelectStatement());
        List<Book> books = bookMapper.selectMany(selectStatementProvider);
        books.forEach(book -> {
            System.out.println("book.isbn() = " + book.getIsbn());
        });
        return books;
    }

    public Book createBook(boolean selective) {
        Book book = book("Hello world", "HISTORY", BigDecimal.valueOf(98.12));

        int count = selective ? bookMapper.insertSelective(book) : bookMapper.insert(book);
        if (count != 1) {
            throw new IllegalStateException("Failed to insert book.");
        }
        return book;
    }

    public List<Book> createBooks() {
        List<Book> bookList = new ArrayList<>();
        bookList.add(book("Hello world", "HISTORY", BigDecimal.valueOf(98.12)));
        bookList.add(book("Hello world", "CHEMISTRY", BigDecimal.valueOf(122.12)));
        int count = bookMapper.insertMultiple(bookList);
        if (count != 2) {
            throw new IllegalStateException("Failed to insert book.");
        }
        return bookList;
    }

    private Book book(String bookName, String bookType, BigDecimal bookPrice) {
        Book book = new Book();
        book.setBookId(BigDecimal.valueOf(System.currentTimeMillis()));
        book.setBookType(bookType);
        book.setBookName(bookName);
        book.setIsbn(generateNumberOnlyString());
        book.setBookPrice(bookPrice);
        book.setCreateDate(new Date());
        book.setCreateUser("admin");
        return book;
    }
}
